#include			"StreamCircularBuffer.h"
#include			<iostream>
StreamCircularBuffer::StreamCircularBuffer(size_t size, size_t packetSize)
{
	_capacity = size;
	_read = 0;
	_write = 0;
	_buffer = new SoundPacket[size];
	for (size_t i = 0; i < _capacity; ++i)
		_buffer[i].setData(new short[packetSize]);
}

StreamCircularBuffer::~StreamCircularBuffer()
{

}

SoundPacket			*StreamCircularBuffer::getPacket()
{
  SoundPacket		*packet;
  _mutex.lock();
  packet = &_buffer[_write];
  _mutex.unlock();
  return packet;
}

void				StreamCircularBuffer::packetReady()
{
  _write = (_write + 1) % _capacity;
}

void				StreamCircularBuffer::next()
{
	_mutex.lock();
	_read = (_read + 1) % _capacity;
	_mutex.unlock();
}

SoundPacket			*StreamCircularBuffer::get()
{
  SoundPacket		*packet;
  _mutex.lock();
  if (_read != _write)
	packet = &_buffer[_read];
  else
	  packet = NULL;
  _mutex.unlock();
  return packet;
}

bool				StreamCircularBuffer::empty()
{
  return _write == _read;
}

size_t				StreamCircularBuffer::size()
{
  if (_write > _read)
    return _write - _read;
  else if (_read > _write)
    return ((_capacity - _read) + _write);
  return 0;
}

size_t				StreamCircularBuffer::capacity()
{
  return _capacity;
}
